"""
A helper function to collect reference stars from apass

By Dr Jie Zheng
v 0.60707 @ 2025-02-01
"""


import numpy as np
import astropy.io.fits as fits
import qastutil as qa
import os


def load(ctra, ctdec, fov=0.6, refhome="/Users/lzj/catalog/"):
    """
    Load APASS reference stars
    :param ctra: center ra
    :param ctdec: center dec
    :param fov: field of view
    :param refhome: home dir for reference
    :return: rra, rdec, rmag
    """

    blockfile = refhome + "apass_block.txt"
    if not os.path.isfile(blockfile):
        raise FileNotFoundError("APASS reference block file not found!")

    # load reference block info
    refall = np.loadtxt(blockfile, dtype=[
            ("blockfile", (str,20)),
            ("dec0", float),
            ("dec1", float),
            ("ra0", float),
            ("ra1", float),
        ], skiprows=1)
    
    # locate block
    refix = (refall["dec0"] < ctdec) & (ctdec < refall["dec1"]) & (refall["ra0"] < ctra) & (ctra < refall["ra1"])
    reffile = refhome + "apass/" + str(refall["blockfile"][refix][0])

    if not os.path.isfile(reffile):
        raise FileNotFoundError("APASS reference file not found!")

    # load all stars from block
    ref = fits.getdata(reffile)

    # only brigher than 16 mag
    ref = ref[ref["V"] < 16.0]

    # distance to the center
    dis = qa.distance(ref["RAdeg"], ref["DECdeg"], ctra, ctdec)
    ref = ref[dis < fov * 0.75]  # 1.5 is a factor to make sure the stars are in the field of view

    # sort by mag
    ref = ref[np.argsort(ref["V"])]

    # extract ra, dec, mag
    rra, rdec, rmag = ref['radeg'], ref['decdeg'], ref['V']

    return rra, rdec, rmag
